package com.gitee.chenyaohua.oa.util.jwt;

import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.Map;

import com.alibaba.fastjson.JSONPath;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.chenyaohua.oa.domain.Payload;
import com.gitee.chenyaohua.oa.from.vo.UserInfoVo;
import com.gitee.chenyaohua.oa.util.secret.SecretUtils;


public class JwtTokenUtil  {
		
	/**
	 * 
	 * @param payloadStr
	 * @param secret	私钥
	 * @return
	 * @throws Exception
	 */
	  public static String generateToken(String payloadStr, String secret) throws Exception {
		  Map<String, String> header = Map.of("alg", "rsa", "typ", "jwt");
		  
		  long currentTimeMillis = System.currentTimeMillis();
		  long exp = currentTimeMillis+30*60*1000;
		  Map<String, Serializable> payload = Map.of("exp", exp, "iss", "http://gitee.com/chenyaohua", "sub", payloadStr, "nbf", currentTimeMillis, "iat", currentTimeMillis);
		  
		  ObjectMapper mapper = new ObjectMapper();
		  String headerEncodeStr = Base64.getEncoder().encodeToString(mapper.writeValueAsString(header).getBytes(Charset.forName("UTF-8")));
		  String payloadEncodeStr = Base64.getEncoder().encodeToString(mapper.writeValueAsString(payload).getBytes(Charset.forName("UTF-8")));
		  
		  StringBuffer sf = new StringBuffer();
		  sf.append(headerEncodeStr);
		  sf.append(".");
		  sf.append(payloadEncodeStr);
		  
          //签名
          String sign = SecretUtils.sign(secret, sf.toString());
	      sf.append(".");
	      sf.append(sign);
	      return sf.toString();
	  }
	  
	  
	  /**
	   * 
	   * @param token
	   * @param secret 公钥
	   * @return
	   */
      public static String verifyToken(String token, String secret) throws Exception  {
    	  String[] split = token.split("\\.");
    	  String[] base64 = {split[0],split[1]};
    	  String join = String.join(".", base64);
    	  boolean verifySign = SecretUtils.verifySign(secret, split[2], join);
    	  if(verifySign) {
			//数据一致验签成功
    		  String payload = new String(Base64.getDecoder().decode(split[1].getBytes()),"UTF-8");
    		  ObjectMapper mapper = new ObjectMapper();
    		  Payload readValue = mapper.readValue(payload, Payload.class);
    		  
    		  if(readValue.getExp() >= System.currentTimeMillis()) {
    			  throw new Exception("token已失效");
    		  }
    		  
			  return readValue.getSub();
    	  }
			
		  throw new Exception("token验签失败");
      }

	/**
	 *
	 * @param token
	 * @param
	 * @return
	 */
	public static String decodeToken(String token) throws IOException {
		String[] split = token.split("\\.");
		byte[] decode = Base64.getDecoder().decode(split[1]);
		return new String(decode, "UTF-8");
	}

}
